package com.vimi8.ebb.auth.manage;

import com.vimi8.ebb.auth.model.*;
import com.vimi8.ebb.auth.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by think on 2016/12/2.
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class UserManageImpl implements UserManage {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    UserAuthorityService userAuthorityService;
    @Autowired
    private DBClientDetailsService dbClientDetailsService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Autowired
    private MyMessageService myMessageService;


    @Override
    public Integer registerUser(RegUser regUser) throws Exception {
        int count = 0;
        int isCreatUser=0;
        //存在ClientId,用户想加入该组织
        for (String clientId : regUser.getApplyClientId()) {
            DBClientDetails clientDetails = null;
            OrganizationDept organizationDept=null;
            clientDetails = dbClientDetailsService.getClientDetailsByClientId(clientId);

            if(clientDetails==null) {
                continue; //当前clientId 无效,继续循环下一个
            }
            //加入 指定的部门
            if(!StringUtils.isEmpty(regUser.getApplyDeptId())){
                organizationDept=userAuthorityService.getOrganizationDept(clientId,regUser.getApplyDeptId());
            }
            //部门不存在,则加入默认部门deptId="0"
            if(organizationDept==null) {
                organizationDept=userAuthorityService.getOrganizationDept(clientId,"0");
                if(organizationDept==null){
                    continue; //默认部门deptId="0" 无效,继续循环下一个
                }
            }
            //clientId 和 deptId正常,且未创建用户
            if(isCreatUser<=0){
                //只执行一次,创建用户
                try {
                    isCreatUser = userAuthorityService.insertOauthUser(regUser);
                    count+=isCreatUser;
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    throw new Exception(e.getMessage());
                }
            }
            //logger.warn("clientDetails:"+clientDetails);
            if (clientDetails.getAllowUsersToJoin()==null || !clientDetails.getAllowUsersToJoin()) {
                //需要审核才能成为client域下的用户,则把申请记录到表里
                count += userAuthorityService.insertUserApplyClient(regUser.getUserId(),clientId,organizationDept.getDeptId());
            }else {
                //根据clientId给用户配置自动资源
                LinkedHashSet<String> resourcesSet=new LinkedHashSet();
                //String resources = "default_resources";
                if (!StringUtils.isEmpty(clientDetails.getAutoResources())) {
                    resourcesSet.addAll(Arrays.asList(clientDetails.getAutoResources().split("\\|"))) ;
                    //resources = clientDetails.getAutoResources();
                }
                //参考 部门,添加部门资源
                if (!StringUtils.isEmpty(organizationDept.getDeptResources())) {
                    resourcesSet.addAll(Arrays.asList(organizationDept.getDeptResources().split("\\|"))) ;
                    //resources = clientDetails.getAutoResources();
                }
                if(resourcesSet.size()==0){
                    resourcesSet.add("default_resources");
                }

                //根据clientId给用户配置自动权限
                LinkedHashSet<String> scopesSet=new LinkedHashSet();
                //String scopes = "default_scopes";
                if (!StringUtils.isEmpty(clientDetails.getAutoScopes())) {
                    scopesSet.addAll(Arrays.asList(clientDetails.getAutoScopes().split("\\|"))) ;
                    //scopes = clientDetails.getAutoScopes();
                }
                //参考 部门,添加部门权限
                if (!StringUtils.isEmpty(organizationDept.getDeptScopes ())) {
                    scopesSet.addAll(Arrays.asList(organizationDept.getDeptScopes().split("\\|"))) ;
                    //resources = clientDetails.getAutoResources();
                }
                if(scopesSet.size()==0){
                    scopesSet.add("default_scopes");
                }

                //查询applyOpenid是否存在,不存在则可使用该applyOpenid
                String openid = UUID.randomUUID().toString();
                if (!StringUtils.isEmpty(regUser.getApplyOpenid()) && userAuthorityService.getOpenIdCount(clientId, regUser.getApplyOpenid()) <= 0) {
                    openid = regUser.getApplyOpenid();
                }
                //用户插入组织(client域)
                //数据库，需保证resources,scopes  NOT NULL（已加约束），所以此处resources,scopes不能为null
                //logger.warn("clientId:"+clientId+",UserId:"+regUser.getUserId()+",openid:"+openid+",resources:"+resources+",scopes:"+scopes);
                count += userAuthorityService.insertOpenid(clientId, regUser.getUserId(), openid,  String.join("|", resourcesSet), String.join("|", scopesSet));
                //插入部门
                count +=userAuthorityService.insertOrganizationEmp(new OrganizationEmp().clientId(clientId).deptId(organizationDept.getDeptId()).userId(regUser.getUserId()));
            }
            //申请手动配置的资源,则把申请记录到表里
            if (regUser.getApplyResources() != null && regUser.getApplyResources().size() > 0 && !StringUtils.isEmpty(clientDetails.getManuResources())) {
                List<String> manuResources= Arrays.asList(clientDetails.getManuResources().split("\\|"));
                for (String resourceId : manuResources) {
                    if (regUser.getApplyResources().contains(resourceId)) {
                        count += userAuthorityService.insertUserApplyClientResource(regUser.getUserId(), clientId, resourceId);
                    }
                }
            }
            //申请手动配置的权限,则把申请记录到表里
            if (regUser.getApplyScopes() != null && regUser.getApplyScopes().size() > 0 && !StringUtils.isEmpty(clientDetails.getManuScopes())) {
                List<String> manuScopes= Arrays.asList(clientDetails.getManuScopes().split("\\|"));
                for (String scope : manuScopes) {
                    if (regUser.getApplyScopes().contains(scope)) {
                        count += userAuthorityService.insertUserApplyClientScope(regUser.getUserId(), clientId, scope);
                    }
                }
            }
        }


        return isCreatUser;
    }
}
